#encoding:utf-8

from django import forms
from django.forms import ModelForm
from models import *
from countries_states.models import Country, State, Municipal
from django.utils.translation import ugettext_lazy as _


def countries():
    """Get country selections."""
    return Country.objects.filter(active=True)


def get_states(country=None):
    """
    Get state selections based on the country parameter.
    """
    choices = [('0', 'No aplica')]
    if country:
        # print type(country)
        if type(country) == long:
            country = Country.objects.get(pk= int(country))
        states = country.state_set.filter(active=True)
        if states.count() > 0:
            choices = [('-1', 'Seleccione...')]
            for state in states:
                choices.append([state.id, state.name])
    return choices


def get_municipals(state=None):
    """
    Get municipal selections based on the state parameter.
    """
    choices = [('0', 'No aplica')]
    if state:
        if type(state) == long:
            state = State.objects.get(pk= int(state))
        municipals = state.municipal_set.all()
        if municipals.count() > 0:
            choices = [('-1', 'Seleccione...')]
            for municipal in municipals:
                choices.append([municipal.id, municipal.name])
    return choices


class AdressForm(forms.ModelForm):
    initial_country = Country.objects.get(iso2_code__exact='MX')
    country = forms.ModelChoiceField(
        queryset=countries(),
        required=True,
        label=_(u'País'),
        empty_label=_(u'Seleccione'),
        initial=Country.objects.get(id=initial_country.id)
    )
    state = forms.ChoiceField(
        choices= get_states(initial_country),
        label=_(u'Estado')
    )
    municipal = forms.ChoiceField(
        choices = get_municipals(None),
        label = _(u'Municipio'),
        required=False
    )
    street = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': _(u'Calle')}),
        max_length=200,
        error_messages={'required': _(u"Ingrese una calle")},
        label=_(u"Calle"),
    )
    postal_code = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': _(u'Código Postal')}),
        max_length=5,
        error_messages={'required': _(u"Ingrese su Código Postal")},
        label=_(u"CP."),
    )
    city = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': _(u'Ciudad o Municipio')}),
        max_length=60,
        error_messages={'required': _(u"Ingrese su Ciudad")},
        label=_(u"Ciudad"),
        )

    def __init__(self, *args, **kwargs):
        change_profile = False
        country_selected = kwargs.pop('country_selected', None)
        state_selected = kwargs.pop('state_selected', None)
        # municipal_selected = kwargs.pop('municipal_selected', None)
        try:
            if kwargs.pop('change_profile'):
                change_profile = True
        except:
            None

        super(AdressForm, self).__init__(*args, **kwargs)

        if change_profile:
            self.fields['state'].choices = get_states(country_selected)
            self.fields['municipal'].choices = get_municipals(state_selected)

        if self.is_bound:
            if not country_selected:
                country_selected = self.initial_country
            if state_selected == 0:
                country_selected = None
                state_selected = None

            self.fields['state'].choices = get_states(country_selected)
            self.fields['municipal'].choices = get_municipals(state_selected)

    def clean_country(self):
        if not self.cleaned_data.get('country'):
            raise forms.ValidationError(_(u'Seleccione un país'))
        return self.cleaned_data['country']

    def clean_state(self):
        state_id = int(self.cleaned_data.get('state'))
        if state_id < 0:
            raise forms.ValidationError(_(u'Seleccione un Estado'))
        if state_id == 0:
            return None
        try:
            country = self.cleaned_data.get('country')
            try:
                states = country.state_set.filter(active=True)
            except:
                states = []
            choices = [0]
            for state in states:
                choices.append(state.id)
            if state_id not in choices:
                raise forms.ValidationError(_(u'Seleccione un Estado'))
                # state = State.objects.get(id=state)
            state = State.objects.get(pk = state_id)
        except State.DoesNotExist:
            raise forms.ValidationError(_(u'El Estado que seleccionó no es válido'))
        return state

    def clean_municipal(self):
        municipal_id = int(self.cleaned_data.get('municipal'))
        if municipal_id < 0:
            raise forms.ValidationError(_(u'Seleccione un Municipio'))
        if municipal_id == 0:
            return None
        try:
            choices = [0]
            try:
                state = self.cleaned_data.get('state')
                state_id = state.pk
                state = State.objects.get(id=state_id)
                municipals = state.municipal_set.all()
                for municipal in municipals:
                    choices.append(municipal.id)
            except:
                return None
            if municipal_id not in choices:
                raise forms.ValidationError(_(u'Seleccione un Municipio'))
                # state = State.objects.get(id=state)
            municipal = Municipal.objects.get(pk = municipal_id)
        except Municipal.DoesNotExist:
            raise forms.ValidationError(_(u'El Municipio que seleccionó no es válido'))
        return municipal

    def save(self, *args, **kwargs):
        new_address = Address.objects.create(
            street=self.cleaned_data['street'],
            postal_code=self.cleaned_data['postal_code'],
            city=self.cleaned_data['city'],
            municipal= self.cleaned_data['municipal'],
            state=self.cleaned_data['state'],
            country=self.cleaned_data['country']
        )
        return new_address

    def update(self, *args, **kwargs):
        address = super(AdressForm, self).save(*args, **kwargs)

        municipal=self.cleaned_data['municipal']

        address.street = self.cleaned_data['street']
        address.postal_code = self.cleaned_data['postal_code']
        address.city = self.cleaned_data['city']
        address.country = self.cleaned_data['country']
        address.state = self.cleaned_data['state']
        address.municipal = self.cleaned_data['municipal']
        address.save()

        if hasattr(self, 'save_profile'):
            self.save_profile(address, *args, **kwargs)

        return address

    class Meta:
        model = Address